/*
 * @(#)EMailUtil.java		       Project:csdn
 * Date:2012-5-31
 *
 * Copyright (c) 2011 CFuture09, Institute of Software, 
 * Guangdong Ocean University, Zhanjiang, GuangDong, China.
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sinaapp.msdxblog.netsecurity.csdn.util;

import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.URLName;

import com.sun.mail.smtp.SMTPTransport;

/**
 * @author Geek_Soledad (66704238@51uc.com)
 */
public class EMailUtil extends SMTPTransport{

	public EMailUtil(Session session, URLName urlname) {
		super(session, urlname);
	}

	/**
	 * 是否可以正常登录邮箱（网易邮箱）。
	 * 
	 * @param account
	 *            邮箱账号
	 * @param password
	 *            密码
	 * @return 成功登录时返回true,否则返回false。
	 */
	private boolean login(String account, String password) {
		String name = account.split("@")[0];
		URLName urlName = new URLName("smtp", "smtp.tom.com", 25, "", name, password);
		boolean hasLogin = true;
		try {
			hasLogin = this.protocolConnect(urlName.getHost(), urlName.getPort(), urlName.getUsername(), urlName.getPassword());
		} catch (MessagingException e) {
			hasLogin = false;
			if(e.getMessage().equals("Could not connect to SMTP host: smtp.163.com, port: 25, response: -1")){
				System.out.println("验证被限制，尝试在10秒后重新验证");
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				hasLogin = new EMailUtil(Session.getInstance(new Properties()), null).login(account, password);
			}
//			System.out.println(name + ":" + password + "验证失败");
		}
		return hasLogin;
	}
	
	/**
	 * 是否可以正常登录邮箱（网易邮箱）。
	 * 
	 * @param account
	 *            邮箱账号
	 * @param password
	 *            密码
	 * @return 成功登录时返回true,否则返回false。
	 */
	public static boolean loginSuccessful(String account, String password) {
		return new EMailUtil(Session.getInstance(new Properties()), null).login(account, password);
	}
	
	public static void main(String[] args) {
		if (loginSuccessful("account", "password")) {
			System.out.println("登录成功"); 
		}
	}
}
